package com.lazyframework.security.web.configuration;

import com.lazyframework.security.web.JwtClients;
import com.lazyframework.security.web.configuration.properties.AuthenticationProperties;
import com.lazyframework.security.web.configuration.properties.AuthorizeProperties;
import com.lazyframework.security.web.configuration.properties.JsonWebTokenProperties;
import com.lazyframework.security.web.exception.UserNotFoundException;
import com.lazyframework.security.web.util.PasswordEncoder;
import com.lazyframework.security.web.util.bcrypt.BCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.servlet.Filter;

/**
 * Create by lazy in 2019/11/7
 */
@EnableConfigurationProperties({
        JsonWebTokenProperties.class,
        AuthorizeProperties.class,
        AuthenticationProperties.class
})
public class WebSecurityConfiguration {

    @Autowired
    private WebSecurityConfigurer<WebSecurity> securityConfigurer;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtClients jwtClients(JsonWebTokenProperties properties) {
        return new JwtClients(properties);
    }

    @Bean
    public Filter securityFilterChain(ApplicationContext context, AuthorizeProperties authorizeProperties) {
        WebSecurity webSecurity = new WebSecurity();
        if (securityConfigurer == null) {
            WebSecurityConfigurerAdapter webSecurityConfigurerAdapter = new WebSecurityConfigurerAdapter() {
            };
            webSecurityConfigurerAdapter.setContext(context);
            webSecurityConfigurerAdapter.setJwtClients(new JwtClients(new JsonWebTokenProperties()));
            webSecurityConfigurerAdapter.setAuthorizeProperties(authorizeProperties);
            webSecurityConfigurerAdapter.setUserDetailsService(id -> {
                throw new UserNotFoundException();
            });
            securityConfigurer = webSecurityConfigurerAdapter;
        }
        webSecurity.apply(securityConfigurer);
        return webSecurity.build();
    }

}
